package com.ruoyi.company.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.company.domain.*;
import com.ruoyi.company.mapper.CompanyMapper;
import com.ruoyi.company.service.*;
import com.ruoyi.company.utils.seal.SealUtils;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductAll;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.scope.domain.Scope;
import com.ruoyi.scope.service.ScopeService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/business/company")
public class CompanyController extends BaseController {

    @Autowired
    ICompanyServer companyServer;

    @Autowired
    ISysUserService iSysUserService;

    @Autowired
    ICompanyOtherServer iCompanyOtherServer;

    @Autowired
    ISysDeptService iSysDeptService;

    @Autowired
    ICompanyInvoiceService iCompanyInvoiceService;

    @Autowired
    ScopeService scopeService;

    @Autowired
    ICompanyScopeServer iCompanyScopeServer;

    @Autowired
    ICompanyServer iCompanyServer;

    @Autowired
    ICompanyLinkmanServer iCompanyLinkmanServer;

    @Autowired
    SysUserServiceImpl sysUserServiceImpl;

    @Autowired
    ISysConfigService iSysConfigService;

    @Autowired
    PurchaseOrderService purchaseOrderService;

    @Autowired
    ISaleorderService iSaleorderService;

    @Autowired
    ICompanyMyLinkmanServer iCompanyMyLinkmanServer;

    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    SysUserMapper userMapper;

    @Autowired
    MonthlyCardMsgService monthlyCardMsgService;

    @Transactional(rollbackFor = {Exception.class})
    @Log(title = "新增我的公司档案", businessType = BusinessType.UPDATE)

    @PostMapping("/addMycompany")
    @ResponseBody
    public AjaxResult addMycompany(@RequestBody Company company) {
        SysUser usera = SecurityUtils.getLoginUser().getUser();
        Long companyId = usera.getCompanyId();

        company.setCompanyId(companyId);

        int updateCompany = companyServer.insertCompany(company);

        // 通知消息
        if (StringUtils.isNotEmpty(company.getMonthlyCard())) {
            MonthlyCardMsg mouthCodeMsg = MonthlyCardMsg.builder()
                    .monthlyCard(company.getMonthlyCard())
                    .companyId(companyId)
                    .companyName(company.getCompanyName())
                    .status("1")
                    .createTime(new Date())
                    .build();
            monthlyCardMsgService.insertMonthlyCardMsg(mouthCodeMsg);
        }

        List<CompanyAddress> list = company.getAddressList();

        for (CompanyAddress companyAddress : list) {
            companyAddress.setCompanyId(companyId);
            companyMapper.insertComPanyAddress(companyAddress);
        }
        //  int updateCompanyInvoice = iCompanyInvoiceService.insertCompanyInvoice(companyInvoice);

        if (updateCompany >= 1) {
            return toAjax(1);
        } else {
            return toAjax(-1);
        }
    }


    @GetMapping("/selectProduct")
    @ResponseBody
    public Map<String, Object> selectProduct(@Param("companyId") Long companyId) {
        Map<String, Object> resMap = new HashMap<>();
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            Product product = new Product();
            product.setDeptId(sysUser.getDeptId());
            product.setCompanyId(companyId);
            List<Product> zhlist = new ArrayList<>();
            List<Product> list = productMapper.selectXxList(product);
            List<Product> sqList = productMapper.selectSQList(product);
            List<Product> productList = productMapper.selectCompanyProduct(product);
            List<Long> prolist = new ArrayList<>();

            for (Product product1 : sqList) {
                prolist.add(product1.getProductId());
            }

            if (sqList.size() != 0) {
                for (Product a1 : list) {
                    if (!prolist.contains(a1.getProductId())) {
                        a1.setSelectId(0L);
                        zhlist.add(a1);
                    }
                }
                for (Product a1 : sqList) {
                    zhlist.add(a1);
                }
                resMap.put("products", zhlist);
            } else {
                for (Product a1 : list) {
                    if (a1.getIsAudit().equals("0")) {
                        a1.setSelectId(0L);
                    }
                    zhlist.add(a1);
                }
                resMap.put("products", list);
            }
            resMap.put("productType", productList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resMap;
    }

    /*
    给对应的合作单位授权产品
     */
    @PostMapping("/auditProduct")
    @ResponseBody
    public AjaxResult auditProduct(@RequestBody ProductAll productAll) {
        companyServer.updateProduct(productAll);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('enterprise:record')")
    @GetMapping("/myconpany")
    public List<Company> mycompany() {
        List<Company> list = new ArrayList<>();
        try {
            SysUser usera = SecurityUtils.getLoginUser().getUser();
            Long companyId = usera.getCompanyId();
            if (companyId != 0 && companyId != null) {
                list = companyServer.mycompany(companyId);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @PostMapping("/importCompany")
    @ResponseBody
    public AjaxResult importCompany(MultipartFile file) {
        try (InputStream input = file.getInputStream()) {
            // KoAosCp koAosCp = aosCpService.importCompany(input);//业务层返回，我需要给前端返回，根据自己需求设置是否有需要返回
            companyServer.importCompany(file.getInputStream());
        } catch (Exception e) {
            String msg = e.getMessage();
            if (StringUtils.isEmpty(msg)) {
                msg = e.getClass().getName();
            }
            e.printStackTrace();
        }
        return AjaxResult.success("");
    }

    /**
     * 根据本公司 company查询 本公司下的部门
     *
     * @return
     */
    @GetMapping("/selectUserAndDept")
    @ResponseBody
    public AjaxResult selectUserAndDept() {
        SysUser usera = SecurityUtils.getLoginUser().getUser();
        Long companyId = usera.getCompanyId();
        Map<String, Long> map = new HashMap<>();
        JSONArray jsonArray1 = new JSONArray();
        map.put("companyId", companyId);
        List<SysUser> sysUsers = companyServer.selectUserAndDept(map);
        //去除重复
        Map<String, Object> hashMap = new HashMap<>();
        if (sysUsers.size() != 0) {
            for (int i = 0; i < sysUsers.size(); i++) {
                SysUser sysUser = sysUsers.get(i);
                hashMap.put(sysUser.getDept().getDeptName(), sysUser.getDept().getDeptId());
            }
            Set<Map.Entry<String, Object>> entries = hashMap.entrySet();
            for (Map.Entry<String, Object> entrie : entries) {
                Object value = entrie.getValue();
                String key = entrie.getKey();
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("name", key);
                jsonObject1.put("value", value);
                jsonArray1.add(jsonObject1);
                AjaxResult.success(jsonArray1);
            }

        } /*else {
            return error("未查询到该公司负责部门及员工信息");
        }*/
        return success(jsonArray1);
    }


    /**
     * 根据选择的部门 带出负责员工
     *
     * @return
     */
    @GetMapping("/selectUser")
    @ResponseBody
    public AjaxResult selectUser(HttpServletRequest httpServletRequest) {
        String deptId = httpServletRequest.getParameter("deptId");
        SysUser usera = SecurityUtils.getLoginUser().getUser();
        Long companyId = usera.getCompanyId();
        Map<String, Long> map = new HashMap<>();
        map.put("deptId", Long.valueOf(deptId));
        JSONArray jsonArray1 = new JSONArray();
        if (deptId != "") {
            map.put("parentId", companyId);
            List<SysUser> sysUsers = companyMapper.selectUserAndDeptUser(map);
            if (sysUsers.size() != 0) {
                for (int i = 0; i < sysUsers.size(); i++) {
                    SysUser sysUser = sysUsers.get(i);
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("name", sysUser.getNickName());
                    jsonObject1.put("value", sysUser.getUserId());
                    jsonArray1.add(jsonObject1);
                }
                return success(jsonArray1);
            } else {
                return error("未查询到负责员工的信息");
            }
        }
        return error("未查询到负责员工的信息");

    }

    /**
     * 查询 合作单位 列表 只展示当前登陆人的合作单位
     */
    @RequiresPermissions("enterprise:record")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(String socialCreditCode, String deptName, String userName) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        startPage();
        Long companyId = user.getCompanyId();
        Map<String, Object> map = new HashMap();
        map.put("deptId", companyId);
        if (!user.getDeptId().equals(user.getCompanyId())) {
            map.put("userId", user.getUserId());
        }
        map.put("deptName", deptName);
        map.put("userName", userName);
        map.put("socialCreditCode", socialCreditCode);
        List<CompanyOther> list = iCompanyOtherServer.selectList(map);

        return getDataTable(list);
    }

    /**
     * 设置 合作单位经营范围
     */
    // @RequiresPermissions("business:company:edit")
    @Transactional(rollbackFor = {Exception.class})
    @Log(title = "设置公司经营范围", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/editScope", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult editScopePost(@RequestBody JSONObject id, @RequestBody JSONObject classArr, @RequestBody JSONObject companyId) {
        String cc = id.getString("id");
        Long UserCompanyId = 0L;
        String deptId = companyId.getString("companyId");
        if (deptId == null) {
            UserCompanyId = SecurityUtils.getLoginUser().getCompanyId();
        } else {
            UserCompanyId = Long.valueOf(deptId);
        }
        if ("".equals(cc) || cc == null) {
            HashMap hashMap = new HashMap();
            hashMap.put("companyId", UserCompanyId);
            return toAjax(iCompanyScopeServer.deleteByCompanyId(hashMap));
        }
        String[] scope = cc.split(",");
        String DD = classArr.getString("classArr");
        String[] split = DD.split(",");

        HashMap hashMap = new HashMap();
        hashMap.put("companyId", UserCompanyId);
        iCompanyScopeServer.deleteByCompanyId(hashMap);
        for (int i = 0; i < scope.length; i++) {
            CompanyScope companyScope = new CompanyScope();
            companyScope.setCompanyId(UserCompanyId);
            companyScope.setScopeId(Long.valueOf(scope[i]));
            companyScope.setScopeClass(split[i]);
            companyScope.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            companyScope.setCreateTime(DateUtils.getNowDate());
            iCompanyScopeServer.insertCompanyScope(companyScope);
        }
        return toAjax(1);

    }

    @GetMapping("/scopeShow")
    public Map<String, Object> scopeShowGet() {
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        Map<String, Object> resMap = new HashMap<>();
        Map<String, Object> reaMap = new HashMap<>();
        resMap.put("companyId", companyId);
        List<CompanyScope> list = iCompanyScopeServer.selectList(resMap);
        List<CompanyScope> allList = iCompanyScopeServer.allList();
        reaMap.put("allList", allList);//全部的经营范围
        reaMap.put("company", list);//公司有的经营范围
        return reaMap;
    }

    @GetMapping("/scopeShow/{companyId}")
    public Map<String, Object> scopeShowGet1(@PathVariable("companyId") Long companyId) {
        Map<String, Object> resMap = new HashMap<>();
        Map<String, Object> reaMap = new HashMap<>();
        resMap.put("companyId", companyId);
        List<CompanyScope> list = iCompanyScopeServer.selectList(resMap);
        List<CompanyScope> allList = iCompanyScopeServer.allList();
        reaMap.put("allList", allList);  //全部的经营范围
        reaMap.put("company", list);  //公司有的经营范围
        return reaMap;
    }

    @GetMapping("/selectCompany")
    public Map<String, Object> selectCompany(@RequestParam Long id) {
        // SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Map<String, Object> resMap = new HashMap<>();
        CompanyOther companyOther = iCompanyOtherServer.selectCompanyOtherById(id);
        Company company = companyMapper.selectCompany(companyOther.getCompanyId());
        List<CompanyAddress> list = companyMapper.selectCompanyAddress(companyOther.getCompanyId());
        if (list.size() != 0) {
            company.setAddressList(list);
        }
        resMap.put("companyOter", companyOther);
        resMap.put("company", company);
        return resMap;
    }

    @GetMapping("/selectQualification")
    public Map<String, Object> selectQualification(@RequestParam Long companyId, @RequestParam String type) {
        Map<String, Object> resMap = new HashMap<>();
        try {
            resMap = iCompanyServer.selectQualification(companyId, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resMap;
    }

    @GetMapping("/selectAlltQualification")
    public Map<String, Object> selectAlltQualification(@RequestParam Long companyId) {
        Map<String, Object> resMap = new HashMap<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        CompanyAudit companyAudit = new CompanyAudit();
        companyAudit.setCompanyId(companyId);
        companyAudit.setAuditcompanyId(sysUser.getDeptId());
        try {
            companyAudit = companyMapper.selectComapnyAudit(companyAudit);
            if (companyAudit == null) {
                resMap.put("result", "未给该公司授权任何资质");
            } else {
                resMap.put("result", companyAudit);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resMap;
    }

    @PostMapping("/saveAudit")
    @ResponseBody
    public AjaxResult saveAudit(@RequestBody CompanyAudit companyAudit) {
        if (companyAudit.getType().equals("0")) {
            iCompanyServer.Quality(companyAudit);
        } else if (companyAudit.getType().equals("1")) {
            iCompanyServer.CoAuthorization(companyAudit);

        } else if (companyAudit.getType().equals("2")) {
            iCompanyServer.SaleAudit(companyAudit);
        }
        return AjaxResult.success();
    }

    @PostMapping("/selectCode/{socialCreditCode}")
    @ResponseBody
    public AjaxResult selectCode(@PathVariable("socialCreditCode") String socialCreditCode) {
        JSONArray jsonArray = new JSONArray();
        if (!"0".equals(socialCreditCode)) {
            Company company = iCompanyServer.selectBySocialCreditCode(socialCreditCode);
            //获取当前登陆人的companyId
            Long deptId = SecurityUtils.getLoginUser().getUser().getCompanyId();
            JSONObject jsonObject = new JSONObject();
            //为空 则穿过来的统一社会信用代码 不在数据库中
            if (company == null) {
                jsonObject.put("exist", 0);
                //不为空 则是在company表中 有这个统一社会信用代码
            } else {
                //判断登录人 是否与该合作单位有合作
                //传入合作单位的companyid 查找deptid是否等于登陆人的deptid 为true则是登陆人的部门和该合作单位已经有合作关系
                Map<String, Object> map = new HashMap<>();
                map.put("companyId", company.getCompanyId());
                map.put("deptId", deptId);
                CompanyOther result = iCompanyOtherServer.selectDeptIdByCompanyId(map);

                //根据 登陆人的 companyId 查询 与输入的socialCreditCode统一编号是否一致 一致的话 不可提交
                SysUser sysUser1 = iCompanyOtherServer.selectUserByCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
                if (result != null) {
                    //您已经跟该合作单位有合作关系，不允许再添加
                    if (result.getDeptId().equals(deptId)) {
                        jsonObject.put("exist", 2);
                    }
                    //您不能与自己公司成为合作单位
                } else if (sysUser1.getUserName().equals(socialCreditCode)) {
                    jsonObject.put("exist", 3);
                } else {
                    Long companyId = company.getCompanyId();
                    JSONObject jsonObject1 = new JSONObject();
                    JSONObject jsonObject2 = new JSONObject();
                    JSONObject jsonObject3 = new JSONObject();
                    JSONObject jsonObject4 = new JSONObject();
                    JSONObject jsonObject5 = new JSONObject();
                    JSONObject jsonObject6 = new JSONObject();
                    JSONObject jsonObject7 = new JSONObject();
                    JSONObject jsonObject8 = new JSONObject();
                    JSONObject jsonObject9 = new JSONObject();
                    JSONObject jsonObject10 = new JSONObject();
                    JSONObject jsonObject11 = new JSONObject();
                    JSONObject jsonObject12 = new JSONObject();
                    JSONObject jsonObject13 = new JSONObject();
                    JSONObject jsonObject14 = new JSONObject();
                    JSONObject jsonObject15 = new JSONObject();
                    JSONObject jsonObject16 = new JSONObject();
                    JSONObject jsonObject17 = new JSONObject();
                    JSONObject jsonObject18 = new JSONObject();
                    JSONObject jsonObject19 = new JSONObject();
                    JSONObject jsonObject20 = new JSONObject();
                    JSONObject jsonObject21 = new JSONObject();

                    //需要传入界面的 值
                    //单位名称

                    jsonObject1.put("deptName", iSysDeptService.selectDeptById(company.getCompanyId()).getDeptName());
                    //营业执照
                    jsonObject2.put("licenseUrl", company.getLicenseUrl());
                    //二级备案凭证照片
                    jsonObject3.put("class2Url", company.getClass2Url());
                    //三级经营许可凭证照片
                    jsonObject4.put("class3Url", company.getClass3Url());
                    //法人代表
                    jsonObject5.put("corporateRepresentative", company.getCorporateRepresentative());
                    //公司地址 province
                    jsonObject6.put("RASProvince", company.getRasProvince());
                    //地址 city
                    jsonObject7.put("RASCity", company.getRasCity());
                    //地址 other_corporate_address
                    jsonObject8.put("RASDistrict", company.getRasDistrict());
                    jsonObject.put("exist", 1);
                    jsonObject9.put("status", 1);
                    jsonObject10.put("RASAddress", company.getRasAddress());
                    jsonObject11.put("shipProvince", company.getShipProvince());
                    jsonObject12.put("shipCity", company.getShipCity());
                    jsonObject13.put("shipDistrict", company.getShipDistrict());
                    jsonObject14.put("shipAddress", company.getShipAddress());
                    jsonObject15.put("taxbillType", company.getTaxbillType());
                    jsonObject16.put("taxRate", company.getTaxRate());
                    jsonObject17.put("depositBank", company.getDepositBank());
                    jsonObject18.put("bankNumber", company.getBankNumber());
                    jsonObject19.put("corporateRegisterPhone", company.getCorporateRegisterPhone());
                    jsonObject20.put("invoiceEmail", company.getInvoiceEmail());
                    jsonObject21.put("contractTerms", company.getContractTerms());

                    jsonArray.add(jsonObject1);
                    jsonArray.add(jsonObject2);
                    jsonArray.add(jsonObject3);
                    jsonArray.add(jsonObject4);
                    jsonArray.add(jsonObject5);
                    jsonArray.add(jsonObject6);
                    jsonArray.add(jsonObject7);
                    jsonArray.add(jsonObject8);
                    jsonArray.add(jsonObject9);
                    jsonArray.add(jsonObject10);
                    jsonArray.add(jsonObject11);
                    jsonArray.add(jsonObject12);
                    jsonArray.add(jsonObject13);
                    jsonArray.add(jsonObject14);
                    jsonArray.add(jsonObject15);
                    jsonArray.add(jsonObject16);
                    jsonArray.add(jsonObject17);
                    jsonArray.add(jsonObject18);
                    jsonArray.add(jsonObject19);
                    jsonArray.add(jsonObject20);
                    jsonArray.add(jsonObject21);

                }
            }
            jsonArray.add(jsonObject);

            return AjaxResult.success(jsonArray);
        } else {
            return AjaxResult.success(jsonArray);
        }
    }

    /**
     * 修改保存合作单位信息
     */
    @Transactional(rollbackFor = {Exception.class})
    @Log(title = "修改保存合作单位信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody Company company, @RequestBody CompanyOther companyOther, @RequestBody SysDept sysDept) {

        int updateCompany = companyServer.updateCompany(company);

        companyServer.updateCompanyAddress(company.getAddressList(), company.getCompanyId());

        int updateCompanyother = iCompanyOtherServer.updateCompanyother(companyOther);
       /* if (companyInvoice.getTaxRate() != 0) {
            iCompanyInvoiceService.updateCompanyInvoice(companyInvoice);
        }*/
        sysDept.setDeptId(companyOther.getCompanyId());
        int updateSysDept = iSysDeptService.updateDept(sysDept);

        if (updateCompany >= 1 && updateCompanyother >= 1) {
            return toAjax(1);
        } else {
            return toAjax(-1);
        }
    }

    @GetMapping("/selectInvoice/{id}")
    public Map<String, Object> editInvoiceGet(@PathVariable("id") Long id) {
        Map<String, Object> resMap = new HashMap<>();
        //登录人的 登录名
        SysUser sysUser1 = SecurityUtils.getLoginUser().getUser();
        String loginName = sysUser1.getUserName();
        //根据登录名 获取当前登陆人的companyId
        Long deptId = iSysUserService.selectUserByLoginName(loginName).getCompanyId();
        //先查询 other表 状态为正常还是已同意
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        CompanyOther companyOther = iCompanyOtherServer.selectCompanyOtherById(id);
        resMap.put("gradeStatus", companyOther.getGradeStatus());
        /*if ("0".equals(companyOther.getGradeStatus())) {

            mmap.addAttribute("readonly", false);
            '[
        } else {
            mmap.addAttribute("readonly", true);
        }*/
        Company company = companyMapper.selectByCompanyId(companyOther.getCompanyId());
        resMap.put("companyInvoice", company);
        return resMap;
    }

    /**
     * 新增合作单位
     */
    //@PreAuthorize("@ss.hasPermi('business:company:view')")
    @Transactional(rollbackFor = {Exception.class})
    @Log(title = "新增合作单位", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody CompanyOther companyOther, @RequestBody Company company, @RequestBody SysDept sysDept) {
        SysUser sysUser1 = SecurityUtils.getLoginUser().getUser();
        //登录人的 登录名
        String userName = sysUser1.getNickName();
        CompanyAudit companyAudit = new CompanyAudit();
        //获取当前登陆人的 CompanyId
        Long deptId = sysUser1.getCompanyId();
        //社会信用代码
        String socialCreditCode = company.getSocialCreditCode();
        SysUser user = iSysUserService.selectUserByLoginName(socialCreditCode);
        //判断社会信用代码是否存在   user为空则是不存在
        if (user == null) {
            sysDept.setDeptName(company.getCompanyName());
            sysDept.setParentId((100L));
            sysDept.setCreateTime(new Date());
            sysDept.setCreateBy(userName);
            iSysDeptService.insertDept(sysDept);
            Long dept_id = sysDept.getDeptId();

            SysUser sysUser = new SysUser();
            sysUser.setUserName(socialCreditCode);
            sysUser.setDeptId(dept_id);
            sysUser.setNickName(sysDept.getDeptName());
            //密码为后六位
            String password = socialCreditCode.substring(socialCreditCode.length() - 6);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUser.setCreateBy(userName);
            sysUser.setCompanyId(sysUser.getDeptId());
            int i = iSysUserService.insertUser(sysUser);

            //取sys_config 中company.userRole
            String s = iSysConfigService.selectConfigByKey("company.userRole");
            String[] split = s.split(",");
            Long[] longs = (Long[]) ConvertUtils.convert(split, Long.class);
            sysUserServiceImpl.insertUserRole(sysUser.getUserId(), longs);

            //插入 合作单位表
            //CompanyId 为刚刚 插入到dept表的id
            company.setCompanyId(dept_id);
            company.setCreateBy(userName);
            int i1 = companyServer.insertCompany(company);

            companyOther.setShareInvoice(null);
            companyOther.setSharePro(null);
            companyOther.setShareScope(null);
            companyOther.setShareZizhi(null);
            companyOther.setCreateBy(userName);
            companyOther.setDeptId(sysUser1.getCompanyId());
            companyOther.setCompanyId(dept_id);

            companyAudit.setAuditcompanyId(sysUser1.getCompanyId());
            companyAudit.setCompanyId(dept_id);
            companyAudit.setQuality("");
            companyAudit.setLegal("");
            companyAudit.setSaleAudit("");
            if (companyMapper.selectComapnyAudit(companyAudit) == null) {
                companyMapper.insertCompanyAudit(companyAudit);
            }
            int i3 = iCompanyOtherServer.insertCompanyOther(companyOther);
            List<CompanyLinkman> linkmanList = companyOther.getLinkmanList();

       /*     if (linkmanList != null) {
                for (int j = 0; j < linkmanList.size(); j++) {
                    CompanyLinkman companyLinkman = linkmanList.get(j);
                    companyLinkman.setDeptId(deptId);
                    companyLinkman.setCompanyId(company.getCompanyId());
                }
                int i4 = iCompanyLinkmanServer.insertCompanyLinkman(linkmanList);
            }*/
            if (i == 1 && i1 == 1 && i3 == 1) {
                return toAjax(1);
            } else {
                return toAjax(-1);
            }
        } else {
            //user不为空 则是该合作单位存在 如果存在 将状态改为 申请中
            companyOther.setGradeStatus("1");
            companyOther.setCreateBy(userName);
            companyOther.setDeptId(deptId);
            companyOther.setCompanyId(user.getCompanyId());
            if ("on".equals(companyOther.getShareInvoice())) {
                companyOther.setShareInvoice("否");
            }
            if ("on".equals(companyOther.getSharePro())) {
                companyOther.setSharePro("否");
            }
            if ("on".equals(companyOther.getShareScope())) {
                companyOther.setShareScope("否");
            }
            if ("on".equals(companyOther.getShareZizhi())) {
                companyOther.setShareZizhi("否");
            }

            int i = iCompanyOtherServer.insertCompanyOther(companyOther);
            List<CompanyLinkman> linkmanList = companyOther.getLinkmanList();

            companyAudit.setAuditcompanyId(deptId);
            companyAudit.setCompanyId(user.getCompanyId());
            companyAudit.setQuality("");
            companyAudit.setLegal("");
            companyAudit.setSaleAudit("");
            if (companyMapper.selectComapnyAudit(companyAudit) == null) {
                companyMapper.insertCompanyAudit(companyAudit);
            }

            //把原来的删掉
          /*  HashMap hashMap = new HashMap();
            hashMap.put("deptId", sysUser1.getCompanyId());
            hashMap.put("companyId", company.getCompanyId());
            //这是原来数据库有的数据
            List<CompanyLinkman> list = iCompanyLinkmanServer.selectLinkman(hashMap);

            //要删除的 id
            ArrayList<Long> arrayList = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                arrayList.add(list.get(j).getLinkmanId());
            }
            if (arrayList.size() > 0) {
                int i1 = iCompanyLinkmanServer.deleteLinkmanById(arrayList);
            }

            if (linkmanList != null) {
                for (int j = 0; j < linkmanList.size(); j++) {
                    CompanyLinkman companyLinkman = linkmanList.get(j);
                    companyLinkman.setDeptId(deptId);
                    companyLinkman.setCompanyId(user.getCompanyId());
                    companyLinkman.setCreateBy(sysUser1.getUserName());
                }
                int i4 = iCompanyLinkmanServer.insertCompanyLinkman(linkmanList);
            }
*/
            if (i == 1) {
                return toAjax(1);
            } else {
                return toAjax(-1);
            }
        }
    }

    //@PreAuthorize("@ss.hasPermi('business:company:view')")
    @Transactional(rollbackFor = {Exception.class})
    @Log(title = "修改保存我的公司档案", businessType = BusinessType.UPDATE)
    @PostMapping("/editMycompany")
    @ResponseBody
    public AjaxResult editMycompany(@RequestBody Company company) {


        // 月卡号更换消息
        MonthlyCardMsg monthlyCardMsg = monthlyCardMsgService.findMonthlyCardMsgByCompanyId(company.getCompanyId());
        if (null != monthlyCardMsg && !company.getMonthlyCard().equals(monthlyCardMsg.getMonthlyCard())) {
            monthlyCardMsg.setOldMonthlyCard(monthlyCardMsg.getMonthlyCard());
            monthlyCardMsg.setMonthlyCard(company.getMonthlyCard());
            monthlyCardMsg.setStatus("1");
            monthlyCardMsgService.updateMonthlyCardMsg(monthlyCardMsg);
        } else if (null == monthlyCardMsg && StringUtils.isNotEmpty(company.getMonthlyCard())) {
            MonthlyCardMsg mouthCodeMsg = MonthlyCardMsg.builder()
                    .monthlyCard(company.getMonthlyCard())
                    .companyId(company.getCompanyId())
                    .companyName(company.getCompanyName())
                    .status("1")
                    .createTime(new Date())
                    .build();
            monthlyCardMsgService.insertMonthlyCardMsg(mouthCodeMsg);
        }

        int updateCompany = companyServer.updateCompany(company);
        List<CompanyAddress> companyAddresses = company.getAddressList();
        companyServer.updateCompanyAddress(companyAddresses, company.getCompanyId());

        //    int updateCompanyInvoice = iCompanyInvoiceService.updateCompanyInvoice(companyInvoice);

        if (updateCompany >= 1) {
            return toAjax(1);
        } else {
            return toAjax(-1);
        }


    }

}
